#
# Copyright Laureano Arcanio 2008
# Released under the MIT License
# laureano.arcanio@gmail.com
#

__all__ = ['save_document', 'build_document']

from lymon.core import Document, Tag
from lymon.model import *
from lymon.model import Page, Tags, Attrs
from tw.lymon import template

#session = Session()

def save_document(document=None, name='new_page', session=None):
	"""
	Save a document structure to a Data Base.
	"""
	if document:
		context = document.context
		page = Page(name=name)
		session.add(page)
		for tag in context:
			if tag['name'] != '__default__':
				_tag = Tags(name = tag['tag'])
				# Returns an Attrs object
				def attr(k, v):
					python = {'attrs': {}, 'id': True, 'widgets': False}
					if k in python.keys():
						v = str(v)
					return Attrs(name=k, value=v)
				
				attrs = [attr(k,v) for k, v in tag.items()]
				session.add_all(attrs)
				for attr in attrs:
					_tag.attrs.append(attr)
				page.tags.append(_tag)
		session.commit()

def build_document(name='new_page', session=None):
	"""
	Returns a Document() instance based on the database Estructure by given page name.
	"""
	if name:
		page = session.query(Page).filter_by(name = name).first()
		if page:
			html = Document()
			tags = page.tags
			for tag in tags:
				attrs = tag.attrs
				attrs = dict([(str(attr.name),  eval_str(attr)) for attr in attrs])
				html.context.append(attrs)
			return html
	
def eval_str(attr):
	"""
	Return a string or eval(string) to build a Tag
	"""
	python = {'attrs': {}, 'id': True, 'widgets': False}
	if attr.name in python.keys():						
		if attr.value == None:
			return python[attr.name]
		return eval(attr.value)
	else:
		if attr.value == None:
			return ''
		else:	
			return str(attr.value)
				
